package com.flyco.modules.returns.controller;

import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONArray;
import com.alibaba.fastjson.JSONObject;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.baomidou.mybatisplus.core.metadata.IPage;
import com.baomidou.mybatisplus.extension.plugins.pagination.Page;
import com.flyco.common.api.vo.Result;
import com.flyco.common.aspect.annotation.AutoLog;
import com.flyco.common.system.query.QueryGenerator;
import com.flyco.common.util.IdGenerator16Bit;
import com.flyco.modules.oms.entity.OmsOrderItem;
import com.flyco.modules.oms.service.IOmsOrderItemService;
import com.flyco.modules.pms.entity.PmsProduct;
import com.flyco.modules.pms.service.IPmsProductService;
import com.flyco.modules.returns.entity.*;
import com.flyco.modules.returns.service.IOmsOrderReturnApplyService;
import com.flyco.modules.returns.service.IOmsOrderReturnItemBatchService;
import com.flyco.modules.returns.service.IOmsOrderReturnItemService;
import com.flyco.modules.stm.entity.StmChannelPrice;
import com.flyco.modules.stm.entity.StmJdChannelPrice;
import com.flyco.modules.stm.entity.StmStoreInfo;
import com.flyco.modules.stm.service.IStmChannelPriceService;
import com.flyco.modules.stm.service.IStmJdChannelPriceService;
import com.flyco.modules.stm.service.IStmStoreInfoService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.BeanUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.util.CollectionUtils;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.HttpServletRequest;
import java.math.BigDecimal;
import java.math.RoundingMode;
import java.util.ArrayList;
import java.util.Arrays;
import java.util.Comparator;
import java.util.List;
import java.util.stream.Collectors;

@Slf4j
@Api(tags = "申请退换货明细")
@RestController
@RequestMapping("/f/returns/omsOrderReturnItem")
public class OmsOrderReturnItemController {

    @Autowired
    private IOmsOrderReturnItemService returnItemService;
    @Autowired
    private IPmsProductService pmsProductService;
    @Autowired
    private IOmsOrderReturnItemBatchService returnItemBatchService;
    @Autowired
    private IOmsOrderItemService orderItemService;
    @Autowired
    private IOmsOrderReturnApplyService returnApplyService;
    @Autowired
    private IStmStoreInfoService storeInfoService;
    @Autowired
    private IStmChannelPriceService channelPriceService;

    @AutoLog(value = "申请退换货明细")
    @ApiOperation(value = "申请退换货明细", notes = "申请退换货明细")
    @GetMapping(value = "/list")
    public Result<?> queryPageList(OmsOrderReturnItem omsOrderReturnItem,
                                   @RequestParam(name = "pageNo", defaultValue = "1") Integer pageNo,
                                   @RequestParam(name = "pageSize", defaultValue = "10") Integer pageSize,
                                   HttpServletRequest req) {
        QueryWrapper<OmsOrderReturnItem> queryWrapper = QueryGenerator.initQueryWrapper(omsOrderReturnItem, req.getParameterMap());
        Page<OmsOrderReturnItem> page = new Page<OmsOrderReturnItem>(pageNo, pageSize);
        IPage<OmsOrderReturnItem> pageList = returnItemService.page(page, queryWrapper);
        return Result.ok(pageList);
    }

    @AutoLog(value = "申请退换货明细")
    @ApiOperation(value = "申请退换货明细", notes = "申请退换货明细")
    @GetMapping(value = "/returnOrderItem")
    public Result<?> getByApplyId(Long applyId) {
        List<OmsOrderReturnItem> list = returnItemService.getByApplyId(applyId);
        if (!CollectionUtils.isEmpty(list)) {
            list = list.stream().sorted(Comparator.comparing(OmsOrderReturnItem::getProductId)).collect(Collectors.toList());
            List<OmsOrderReturnItemVO> returnItemVOList = new ArrayList<>();
            list.forEach(item -> {
                OmsOrderReturnItemVO itemVO = new OmsOrderReturnItemVO();
                BeanUtils.copyProperties(item, itemVO);
                itemVO.setRealReturnSkuUnitCount(itemVO.getRealUnitQuantity() / itemVO.getProductSkuSpec());
                itemVO.setRealReturnUnitCount(itemVO.getRealUnitQuantity() % itemVO.getProductSkuSpec());
                itemVO.setSkuUnitPrice(item.getBoxPrice());
                returnItemVOList.add(itemVO);
            });
            return Result.ok(returnItemVOList);
        }
        return Result.ok(null);

    }


    @AutoLog(value = "删除退货明细")
    @ApiOperation(value = "删除退货明细", notes = "删除退货明细")
    @GetMapping(value = "/deleteItemById/{itemId}")
    @Transactional
    public Result<?> deleteItemById(@PathVariable("itemId") Long itemId) {

        OmsOrderReturnItem itemInfo = returnItemService.getById(itemId);

        Boolean result = returnItemService.removeById(itemId);

        //同时删除批次里面的该商品信息
        List<OmsOrderReturnItemBatch> returnItemBatchList = returnItemBatchService.getByApplyId(itemInfo.getReturnApplyId());
        if (!CollectionUtils.isEmpty(returnItemBatchList)) {
            List<Long> batchIds = returnItemBatchList.stream()
                    .filter(o -> o.getProductId().equals(itemInfo.getProductId()))
                    .map(OmsOrderReturnItemBatch::getId)
                    .collect(Collectors.toList());
            returnItemBatchService.removeByIds(batchIds);
        }

        if (result) {
            return Result.ok("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    @AutoLog(value = "增加退货商品信息")
    @ApiOperation(value = "增加退货商品信息", notes = "增加退货商品信息")
    @GetMapping(value = "/addApplyItem")
    public Result<?> addApplyItem(@RequestParam("productIds") String productIds, @RequestParam("applyId") Long applyId) {

        List<Long> productIdList = new ArrayList<>();
        List<String> productIdStr = Arrays.asList(productIds.split(","));
        for (String id : productIdStr) {
            productIdList.add(Long.valueOf(id));
        }
        OmsOrderReturnApply applyInfo = returnApplyService.getById(applyId);
        StmStoreInfo storeInfo = storeInfoService.getById(applyInfo.getStoreId());

        List<PmsProduct> productList = pmsProductService.getAllByIds(productIdList);
        List<StmChannelPrice> channelPriceList = channelPriceService.getByChannelId(storeInfo.getChannelId());
        List<StmChannelPrice> storeChannelPriceList = channelPriceService.getByStoreId(storeInfo.getId());
        List<OmsOrderReturnItem> returnItemList = new ArrayList<>();
        for (PmsProduct product : productList) {

            //获取产品价格
            OmsOrderItem item = orderItemService.getByStoreIdAndProductId(storeInfo.getStoreId(), product.getId());
            BigDecimal price = new BigDecimal(0);

            //根据渠道获取价格
            if (!CollectionUtils.isEmpty(storeChannelPriceList)) {
                List<StmChannelPrice> priceList = storeChannelPriceList.stream().filter(o -> o.getSkuCode().equals(product.getSkuCode())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(priceList)) {
                    price = priceList.get(0).getPrice();
                }
            } else if (!CollectionUtils.isEmpty(channelPriceList)) {
                List<StmChannelPrice> priceList = channelPriceList.stream().filter(o -> o.getSkuCode().equals(product.getSkuCode())).collect(Collectors.toList());
                if (!CollectionUtils.isEmpty(priceList)) {
                    price = priceList.get(0).getPrice();
                }
            }
            if (price.equals(new BigDecimal(0)) && item != null) {
                //从产品表获取价格
                price = product.getPrice();
            }

            if (price.equals(new BigDecimal(0))) {
                //从产品表获取价格
                price = product.getPrice();
                if (price == null) {
                    return Result.error("请维护商品价格");
                }
            }

            OmsOrderReturnItem returnItem = new OmsOrderReturnItem();
            returnItem.setProductId(product.getId());
            returnItem.setProductName(product.getName());
            returnItem.setProductSkuCode(product.getSkuCode());
            returnItem.setPrice(price.divide(new BigDecimal(product.getSkuSpec()), 2, RoundingMode.UP));
            returnItem.setBoxPrice(product.getPrice());
            returnItem.setProductSkuSpec(Integer.valueOf(product.getSkuSpec()));
            returnItem.setProductPic(product.getPic());
            returnItem.setId(IdGenerator16Bit.generateId());
            returnItem.setProductSkuUnit(product.getSkuUnit());
            returnItem.setProductUnit(product.getUnit());
            returnItem.setReturnApplyId(applyId);
            returnItem.setMinUnitQuantity(0);
            returnItem.setTotalAmount(new BigDecimal(0));
            returnItem.setProductCount(0);
            returnItemList.add(returnItem);
        }
        returnItemService.saveBatch(returnItemList);
        return Result.ok("添加成功");
    }


    @AutoLog(value = "删除凭证")
    @ApiOperation(value = "删除凭证", notes = "删除凭证")
    @PostMapping(value = "/deleteCertificate")
    @Transactional
    public Result<?> deleteCertificate(@RequestBody OmsOrderReturnItem item) {

        OmsOrderReturnItem itemInfo = returnItemService.getById(item.getId());
        itemInfo.setReturnCertificate(item.getReturnCertificate());
        Boolean result = returnItemService.updateById(itemInfo);

        if (result) {
            return Result.ok("删除成功");
        } else {
            return Result.error("删除失败");
        }
    }

    @AutoLog(value = "上传凭证")
    @ApiOperation(value = "上传凭证", notes = "上传凭证")
    @PostMapping(value = "/uploadCertificate")
    @Transactional
    public Result<?> uploadCertificate(@RequestBody OmsOrderReturnItem item) {

        OmsOrderReturnItem itemInfo = returnItemService.getById(item.getId());

        List<ReturnFileVO> fileVOList = JSONObject.parseArray(itemInfo.getReturnCertificate(), ReturnFileVO.class);
        if(fileVOList==null){
            fileVOList=new ArrayList<>();
        }
        ReturnFileVO returnFileVO = JSONObject.parseObject(item.getReturnCertificate(), ReturnFileVO.class);
        fileVOList.add(returnFileVO);
        itemInfo.setReturnCertificate(JSONArray.toJSONString(fileVOList));
        Boolean result = returnItemService.updateById(itemInfo);
        if (result) {
            return Result.ok("上传成功");
        } else {
            return Result.error("上传失败");
        }
    }

}
